<template>
	<s-layout title="购物车">
		<template v-if="state.total >= 1 && state.loading">
			<!-- <view class="fun-btn ss-m-y-40 ss-p-x-30" @click="onchangeStatus">{{state.pageStatus ? '取消' : '管理'}}</view> -->
			<view class="cart-list ss-flex flex-wrap justify-center align-center ss-p-t-40">
				<view class="cart-item ss-p-t-30 ss-p-x-30 ss-m-b-20" v-for="(item,index) in state.list" :key="index">
					<view class="cart-title ss-flex ss-m-b-30">
						<view class="select" @click="onChoiceStore(index)">
							<!-- 选中了且页面是结算状态 -->
							<image class="1"
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-yes.png"
								mode="" v-show="item.select && !state.pageStatus"></image>
							<!-- 没选中且页面是结算状态 -->
							<image class="2"
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-no.png"
								mode="" v-show="!item.select && !state.pageStatus"></image>
							<!-- 选中了且页面是管理状态 -->
							<image class="3"
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-yes.png"
								mode="" v-show="item.delete_select && state.pageStatus"></image>
							<!-- 没选中且页面是管理状态 -->
							<image class="4"
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-no.png"
								mode="" v-show="!item.delete_select && state.pageStatus"></image>
						</view>
						<view class="go-info ss-flex justify-start align-center" @click="sheep.$router.go('/pages/merchant/info', {
                      id:item.store.id,
                    })">
							<view style="max-width: 550rpx;" class="go-text ss-line-1">{{item.store.name}}</view>
							<uni-icons type="right" size="16" color="#494949"></uni-icons>
						</view>
					</view>
					<view class="cart-goods ss-flex align-center ss-m-b-30" v-for="(value,page) in item.goods"
						:key="page">
						<view class="select" @click="onChoiceGroup(index,page)">
							<!-- 选中了且页面是结算状态 -->
							<image
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-yes.png"
								mode="" v-show="value.select && !state.pageStatus"></image>
							<!-- 没选中且页面是结算状态 -->
							<image
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-no.png"
								mode="" v-show="!value.select && !state.pageStatus"></image>
							<!-- 选中了且页面是管理状态 -->
							<image
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-yes.png"
								mode="" v-show="value.delete_select && state.pageStatus"></image>
							<!-- 没选中且页面是管理状态 -->
							<image
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-no.png"
								mode="" v-show="!value.delete_select && state.pageStatus"></image>
						</view>
						<view class="goods ss-flex align-center">
							<image class="goods-image ss-m-r-20" :src="sheep.$url.cdn(value.goods_info.image)"
								mode="aspectFill"></image>
							<view class="goods-text ss-flex justify-between align-start flex-column">
								<view class="name ss-line-1">{{value.goods_info.title}}</view>
								<view class="w-100 ss-flex justify-between align-center">
									<view class="price">
										￥{{value.goods_info.price}}
									</view>
									<view class="ss-flex justify-center align-center" v-show="!state.pageStatus">
										<image class="num-image" @click="NumDown(index,page)"
											src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-down.png"
											mode=""></image>
										<view class="num-text ss-m-x-30">{{value.goods_num}}</view>
										<image class="num-image" @click="NumUp(index,page)"
											src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-up.png"
											mode=""></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="width: 100rpx;height: 250rpx;"></view>
			<view class="bottom-box ss-safe-bottom">
				<view class="ss-p-y-30 ss-p-x-24">
					<view class="btn-box ss-flex justify-between align-center">
						<view class="left ss-flex align-center" @click="onChoiceAll">
							<view class="select">
								<image
									src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-yes.png"
									mode="" v-if="selectAll"></image>
								<image
									src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/group/group-cart-select-no.png"
									mode="" v-else></image>
							</view>
							<view>全部</view>
						</view>
						<view class="right ss-flex align-center">
							<view class="price" v-show="!state.pageStatus">
								<view class="sum-price ss-flex justify-end">
									<view class="left">合计:</view>
									<view class="right">￥{{sum_price}}</view>
								</view>
								<view class="discount-price ss-flex justify-center align-center" @click="open">
									<view class="ss-m-r-5">已优惠￥{{state.discount}} 优惠明细</view>
									<uni-icons type="down" size="16" color="#35C7A8"></uni-icons>
								</view>
							</view>
							<view class="btn ss-m-l-20" @click="confirm">
								<text v-show="state.pageStatus">删除</text>
								<text v-show="!state.pageStatus">结算({{sum_num}})</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</template>
		<s-empty v-if="state.total === 0 && state.loading"
			icon="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/soldout-empty.png" text="暂无数据">
		</s-empty>
		<discountCart :show="state.show" :list="state.list" @close="close"></discountCart>
	</s-layout>
</template>

<script setup>
	import {
		computed,
		reactive
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import {
		cloneDeep
	} from 'lodash';
	import discountCart from './components/discount-cart.vue'

	const state = reactive({
		page: 1,
		total: 1,
		list: [],
		pageStatus: false, // 结算还是管理
		loading: false,
		show:false,
		discount:'￥0'
	})

	// 计算结算价
	const sum_price = computed(() => {
		let totalPrice = () => {
			return state.list.reduce((total, item) => {
				return total + item.goods.reduce((subTotal, value) => {
					return value.select ? subTotal + value.goods_num * Number(value.goods_info
						.price) : subTotal;
				}, 0);
			}, 0);
		};
		return sheep.$helper.numFunc(totalPrice())
	});


	// 计算结算数
	const sum_num = computed(() => {
		return state.list.reduce((total, item) => {
			return total + item.goods.reduce((subTotal, value) => {
				return value.select ? subTotal + value.goods_num : subTotal;
			}, 0);
		}, 0);
	});

	// 计算是否全部选中
	const selectAll = computed(() => {
		if (state.pageStatus) {
			return state.list.every(item => item.delete_select);
		}
		return state.list.every(item => item.select);
	})

	onLoad(() => {
		getData()
	})

	const close = () => {
		state.show = false
	}

	const open = () => {
		if (sum_num.value === 0) {
			return 
		}
		state.show = true
	}
	
	const confirm = async () => {
		if (state.pageStatus) {
			const list = state.list.flatMap(item =>
				item.goods.filter(value => value.delete_select).map(value => ({
					goods_id: value.goods_info.id,
					goods_num: value.goods_num,
					goods_sku_price_id: 0,
					type: "dec"
				}))
			);
			// 每次只能删除一件团购商品
			if (list.length > 1) {
				return uni.showToast({
					title: '单次只可删除一件团购商品!',
					icon: 'none',
					duration: 1500
				})
			}

			deleteCart(list[0])
		} else {
			if (sum_num.value === 0) {
				return 
			}
			const list = state.list.flatMap(item =>
				item.goods.filter(value => value.select).map(value => ({
					goods_id: value.goods_info.id,
					goods_num: value.goods_num,
				}))
			);
			const show_list = state.list.flatMap(item =>
				item.goods
				.filter(value => value.select)
				.map(value => ({
					name: item.store.name,
					id:item.store.id,
					...value
				}))
			);
			console.log(show_list)
			sheep.$store('cart').changeGroupList(show_list)
			sheep.$router.go('/pages/merchant/confirmCart', {
				list: JSON.stringify(list),
				sum_price:sum_price.value,
				sum_num:sum_num.value,
				discount_price:state.discount
			})
		}
	}
	
	// 计算优惠价
	const discount_price = ()=>{
		state.discount = state.list.reduce((total, item) => {
			return total + item.goods.reduce((subTotal, value) => {
				// 判断是否设置了折扣
				if (value.goods_info.is_discount === 1 && value.select) {
					
					return subTotal + (parseFloat(value.goods_info.original_price) - parseFloat(value.goods_info.price)).toFixed(2) * value.goods_num;				
				}
				return subTotal;
			}, 0);
		}, 0);
	}

	const onchangeStatus = () => {
		state.pageStatus = !state.pageStatus
		if (!state.pageStatus) {
			let mode = 'delete_select'
			state.list.forEach(item => {
				item[mode] = false
				item.goods.forEach(value => {
					value[mode] = false
				})
			})
		}
	}

	const onChoiceAll = () => {
		let mode = state.pageStatus ? 'delete_select' : 'select'
		let status = selectAll.value
		state.list.forEach(item => {
			item[mode] = !status
			item.goods.forEach(value => {
				value[mode] = !status
			})
		})
		discount_price()
	}

	// 设置某个团购商品的选中状态
	const onChoiceGroup = (index, page) => {
		const isDeleteMode = state.pageStatus;
		const goods = state.list[index].goods;
		const targetGood = goods[page];
		// 切换选中状态
		targetGood[isDeleteMode ? 'delete_select' : 'select'] = !targetGood[isDeleteMode ? 'delete_select' : 'select'];

		// 更新商家状态
		state.list[index][isDeleteMode ? 'delete_select' : 'select'] = goods.every(item => item[isDeleteMode ?
			'delete_select' : 'select']);
		
		discount_price()
	}

	// 设置某个商家的选中状态
	const onChoiceStore = (index) => {
		let is = !storeSelect(index)
		for (const item of state.list[index].goods) {
			// 根据页面状态设置
			state.pageStatus ? item.delete_select = is : item.select = is
		}
		state.pageStatus ? state.list[index].delete_select = is : state.list[index].select = is
		discount_price()
	}

	// 计算某个商家是否全部选中
	const storeSelect = (index) => {
		if (state.pageStatus) {
			return state.list[index].goods.every(item => item.delete_select);
		}
		return state.list[index].goods.every(item => item.select);
	}

	const NumDown = async (index, page) => {
		if (state.list[index].goods[page].goods_num === 1) {
			let obj = {
				goods_id:state.list[index].goods[page].goods_info.id,
				goods_num: state.list[index].goods[page].goods_num,
				goods_sku_price_id: 0,
				type: "dec"
			}
			
			deleteCart(obj)
			return
		}
		state.list[index].goods[page].goods_num--
		let obj = {
			goods_id: state.list[index].goods[page].goods_info.id,
			goods_num: state.list[index].goods[page].goods_num,
			goods_sku_price_id: 0,
			type: "cover"
		}
		const {
			error,
			data
		} = await sheep.$api.merchant.groupAddCart(obj);
		
		discount_price();
		
	}

	const NumUp = async (index, page) => {
		if (state.list[index].goods[page].goods_num >= state.list[index].goods[page].goods_info.stocks) {
			return
		}
		state.list[index].goods[page].goods_num++
		let obj = {
			goods_id: state.list[index].goods[page].goods_info.id,
			goods_num: state.list[index].goods[page].goods_num,
			goods_sku_price_id: 0,
			type: "cover"
		}
		const {
			error,
			data
		} = await sheep.$api.merchant.groupAddCart(obj)
		
		discount_price();
	}

	const getData = async () => {
		await sheep.$store('cart').getGroupList()
		state.list = sheep.$store('cart').groupList;
		console.log('state.list:',state.list);
		discount_price()
		state.loading = true
		if (state.list.length < 1) {
			state.total = 0
		}
	}
	
	
	const deleteCart = async (obj) => {
		const {
			error,
			data
		} = await sheep.$api.merchant.groupAddCart(obj)
		
		if (error === 0) {
			uni.showToast({
				title: '删除成功!',
				icon: 'none',
				duration: 1500
			})
			await sheep.$store('cart').getGroupList()
			getData()
		}
	}
</script>

<style scoped lang="scss">
	view {
		box-sizing: border-box;
	}

	.fun-btn {
		text-align: right;
		font-weight: 400;
		font-size: 28rpx;
		color: #8A8A8A;
	}

	.cart-list {
		.cart-item {
			width: 702rpx;
			background: #FFFFFF;
			border-radius: 20rpx;

			.cart-goods {
				.goods {
					flex: 1;

					.goods-image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 10rpx;
					}

					.goods-text {
						flex: 1;
						height: 120rpx;

						.name {
							width: 100%;
							font-weight: 500;
							font-size: 32rpx;
							color: #2A2A2A;
						}

						.price {
							height: 40rpx;
							line-height: 40rpx;
							font-weight: bold;
							font-size: 26rpx;
							color: #282828;
						}


						.num-image {
							width: 40rpx;
							height: 40rpx;
						}

						.num-text {
							font-weight: 400;
							font-size: 26rpx;
							color: #282828;
						}
					}
				}
			}
		}
	}

	.bottom-box {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 999;
		background-color: #FFFFFF;

		.btn-box {
			.left {
				font-weight: 400;
				font-size: 24rpx;
				color: #7C7C7C;
			}

			.right {
				.price {
					.sum-price {
						.left {
							font-weight: 400;
							font-size: 24rpx;
							color: #585858;
						}

						.right {
							font-weight: 500;
							font-size: 34rpx;
							color: #35C7A8;
						}
					}

					.discount-price {
						font-weight: 400;
						font-size: 24rpx;
						color: #35C7A8;
					}
				}

				.btn {
					width: 240rpx;
					height: 80rpx;
					background: #35C7A8;
					border-radius: 40rpx;
					font-weight: 500;
					font-size: 30rpx;
					color: #FFFFFF;
					line-height: 80rpx;
					text-align: center;
				}
			}
		}
	}

	.select {
		width: 30rpx;
		height: 30rpx;
		margin-right: 16rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.go-info {
		.go-text {
			height: 40rpx;
			line-height: 40rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #343434;
		}
	}
</style>